/*
 * Copyright © 2017-2018 All Rights Reserved
 * 上海仰空网络科技有限公司 版权所有
 */

package org.chw.callback.handler;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.chw.core.utils.ObjectMapperUtil;
import org.chw.callback.vo.RequestLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * @className RequestHandler
 * @description 请求拦截器
 */
public class RequestHandler extends HandlerInterceptorAdapter {

  private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    Map<String, Object> headMap = new HashMap<String, Object>();
    Map<String, Object> paramMap = new HashMap<String, Object>();

    // 请求url
    String url = request.getRequestURL().toString();
    // 请求方式
    String method = request.getMethod();
    // 请求header信息
    Enumeration<String> headerEnumeration = request.getHeaderNames();
    while (headerEnumeration.hasMoreElements()) {
      String name = headerEnumeration.nextElement();
      headMap.put(name, request.getHeader(name));
    }
    Enumeration<String> parameterEnumeration = request.getParameterNames();
    while(parameterEnumeration.hasMoreElements()){
        String parameterName = parameterEnumeration.nextElement();
        paramMap.put(parameterName,request.getParameter(parameterName));
    }
    RequestLog requestLog = new RequestLog();
    requestLog.setUrl(url);
    requestLog.setReqMethod(method);
    requestLog.setReqHead(headMap);
    requestLog.setReqParam(paramMap);
    LOGGER.info("request:{}", ObjectMapperUtil.getObjectMapper().writeValueAsString(requestLog));
    return true;
  }
}
